var InvestorAdd = function () {

	var handleValidation = function() {
            var formAdd = $('#addForm');
            jQuery.validator.addMethod("mobileLength", function(value, element) {
            	var flag = !checkMobile(value.trim());
            	return flag;
            }, "联系电话输入有误.");
            var validator = formAdd.validate({
                focusInvalid: true,
                rules: {
                	name: {
                        required: true
                    },
                    mobile:{
                    	required: true,
                    	mobileLength:true,
                    	number:true,
                    	rangelength:[10,12],
                        remote: {
                            url: ctx + "/investor/check",
                            type: "post",
                            dataType: "json",
                            data: {type : 1}
                        }
                    },
                    email:{
                        email: true,
                        rangelength:[1,120]
                    },
                    phone:{
                    	number:true
                    },
                    idcard:{
                    	rangelength:[4,21],
                        remote: {
                            url: ctx + "/investor/check",
                            type: "post",
                            dataType: "json",
                            data: {type : 2}
                        }
                    },
                    company:{
                    	rangelength:[0,128]
                    },
                    address:{
                    	rangelength:[0,128]
                    },
                    remark:{
                    	rangelength:[0,512]
                    }
                },
                messages:{
                    name:{
                        required:"姓名不能为空",
                        remote:""
                      },
                    mobile:{
                    	required:"联系电话不能为空",
                    	number:"联系电话输入有误",
                    	rangelength:"请输入正确长度的联系电话",
                        remote:"该联系电话已经被注册"
                      },
                    email:{
                      email:"E-mail地址不正确",
                      rangelength:"E-mail格式长度太长"
                    },
                    phone:{
                    	number:"电话输入有误"
                    },
                    idcard:{
                    	rangelength:"证件号码长度必须为5-21位",
                        remote:"该证件信息已经被注册"
                    },
                    company:{
                    	rangelength:"公司名称不能超过128字符"
                    },
                    address:{
                    	rangelength:"详细地址不能超过128字符"
                    },
                    remark:{
                    	rangelength:"备注不能超过512字符"
                    }
                },
                success: function (label, element) {
                    var icon = $(element).parent('.input-icon').children('i');
                    $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                    icon.removeClass("fa-warning").addClass("fa-check");
                },

                submitHandler: function (form) {
                	var num = $('#idcard_val').val();
                	var mobile = $('#mobile').val();
                	var idType = $('#idType').val();
                	if(checkMobile(mobile)){
                		showError('联系电话输入有误，请检查.',2000,true);
                		return;
                	}
                	var birthdayTime = $('#datetimepicker').val();
                    var a = (Date.parse(new Date()) - Date.parse(birthdayTime))/3600/1000;
                    if (a < 0) {
                    	showError('出生日期填写错误.',2000,true);
                    	return;
                    }
                    if(num != '' && idType == ''){
                    	showError('请选择您的证件类型.',2000,true);
                    	return;
                	}
                    if(num == '' && idType != ''){
                    	showError('请输入您的证件信息.',2000,true);
                    	return;
                	}
                	if(!IDCardCheck(num) && num != '' && idType == '身份证'){
                		showError('您的身份证信息输入有误，请检查.',2000,true);
                		return;
                	}
                    var json = $('form#addForm').serializeJSON();
                    var se1 = $('#selGroupId')[0];
                	var lenth = se1.length;
                	var groupId = [];
                    for(var i =0;i<lenth;i++ ) {
                    	groupId.push(se1[i].value);
                    }
                    var js = json.replace('}', ',');
                	json = js + "\"groupId\":\""+groupId+"\"}";
                    var str = json;
                    $('#btn_submit').attr('disabled',true);
                    $.ajax({
                    	type:"post",
                        contentType:"application/json; charset=UTF-8",
                        url: ctx + "/investor/doAdd",
                        data:json,
                        dataType:"json",
                        success: function(msg){
                        	if(msg.code == 1){
                        		if($('#editorPanelButtons').css('display') == 'block'){
                        			swf2.call("upload");
                        		}
                            	$("#avatarUrl").val('');
                            	swal({
                        	        title: "温馨提示",
                        	        text: "新增投资人成功,是否现在为投资人分配专属理财师？",
                        	        type: "success", 
                        	        showCancelButton: true,
                        	        confirmButtonColor: "#DD6B55",
                        	        cancelButtonText: "稍后分配",
                        	        confirmButtonText: "马上分配",
                        	        closeOnConfirm: false
                        	    }, function (isConfirm) {
							        if(isConfirm){
							        	swal({title:"",timer:10});
							        	$("#deal_Emp").click();
							        	$("#employeeName").html('');
							        	$("#employeeNo").html('');
							        }else{
							        	location.reload();
							        }
								});
                        	}else if(msg.code == 0){
                        		showError(msg.message,3000);
                        	}
                        	$('#btn_submit').attr('disabled',false);
                        },
                        error: function (msg) {
                        	bootbox.alert("服务器偷了个小懒,新增投资人失败了！");
                        }
                    });
                }
            });
    }

    return {
        init: function () {
            handleValidation();
        }
    };
}();

$('#datetimepicker').datepicker(
	{
		autoclose:true
	}
);

/**
 * 左右列表切换功能
 * @param zhangyz
 * @param 2015年8月9日
 */
function add() {
	var se1 = $('#selGroupId')[0];
	var se2 = $('#unselGroupId')[0];
	var lenth = se1.length;
	var i=0;
    for(;i<lenth; ) {
        if(se1[i].selected) {
            var opt = document.createElement('option');
            opt.value = se1[i].value;
            var node = document.createTextNode(se1[i].innerHTML);
            opt.appendChild(node);
            se2.appendChild(opt);
            se1.removeChild(se1[i]);
            lenth = lenth -1;
            i=0
        }
        else{
        	i++;
        }
    }
}
function plu() {
	var se1 = $('#selGroupId')[0];
	var se2 = $('#unselGroupId')[0];
	var lenth = se2.length;
	var i=0;
    for(;i<lenth;) {
        if(se2[i].selected) {
            var opt = document.createElement('option');
            opt.value = se2[i].value;
            var node = document.createTextNode(se2[i].innerHTML);
            opt.appendChild(node);
            se1.appendChild(opt);
            se2.removeChild(se2[i]);
            lenth = lenth -1;
            i=0
        }else{
        	i++;
        }
    }
}

/**
 * 头像切割上传功能
 * @param zhangyz
 * @param 2015年8月8日
*/
swfobject.addDomLoadEvent(function () {
    var webcamAvailable = false;
    var currentTab = 'upload';
    var callback = function (msg) {
		var id = this.id;
        switch (msg.code) {
	        case 1 :break;
	        case 2 :$('#editorPanelButtons').css('display','block');break;
	        case 3 :
	            if(msg.type == 0)
	            {
	                alert("摄像头已准备就绪且用户已允许使用。");
	            }
	            else if(msg.type == 1)
	            {
	                alert("摄像头已准备就绪但用户未允许使用！");
	            }
	            else
	            {
	                alert("摄像头被占用！");
	            }
	            break;
	        case 5 : 
	        	if(msg.type == 0){
	        		document.getElementById("btn_canecl").onclick();
	        	}
				if(msg.type == 1){
					bootbox.alert('头像上传失败，原因：' + msg.content.msg);//原因：上传的原图文件大小超出限值了！           		
				}
				if(msg.type == 2){
					bootbox.alert('头像上传失败，原因：指定的上传地址不存在或有问题！');
				}
				if(msg.type == 3){
					bootbox.alert('头像上传失败，原因：发生了未知错误！');//出现异常
				}
			break;
        }
    };
    var swf2 = new fullAvatarEditor('swf2', 360,{
		id : 'swf2',
		upload_url: ctx+"/investor/avatarnew?id="+document.getElementById("investor_id").value,	//上传图片的接口地址
		method :'post',
        tab_visible : false,				//不显示选项卡，外部自定义
        button_visible : false,				//不显示按钮，外部自定义
        src_upload : 0,						//是否上传原图片的选项：2-显示复选框由用户选择，0-不上传，1-上传
        checkbox_visible : false,			//不显示复选框，外部自定义
        browse_box_align : 38,				//图片选择框的水平对齐方式。left：左对齐；center：居中对齐；right：右对齐；数值：相对于舞台的x坐标
		webcam_box_align : 38,				//摄像头拍照框的水平对齐方式，如上。
		avatar_sizes : '150*150',			//定义单个头像
		avatar_sizes_desc :'258*200像素',	    //头像尺寸的提示文本
		isShowUploadResultIcon:true,		//在上传完成时（无论成功和失败），是否显示表示上传结果的图标。
		avatar_intro : '提交后最终会生成下面的头像效果',
		avatar_tools_visible:true			//是否显示颜色调整工具
    }, callback);
    //复选框事件
    $('#src_upload').change(function () {
        swf2.call('srcUpload', this.checked);
    });
    /*//点击上传按钮的事件
    document.getElementById("upload").onclick=function(){
        swf2.call("upload");
    };*/
    //点击取消按钮的事件
    document.getElementById("btn_canecl").onclick=function(){
        var activedTab = 'upload';
        swf2.call('changepanel', activedTab);
        //隐藏所有按钮
        $('#editorPanelButtons,#webcamPanelButton').hide();
    };
});

/**
 * 省市区级联功能
 * @param zhangyz
 * @param 2015年8月11日20:18:19
 */
function load_province(id,file){                                               //加载省份
	file = file ? file : (ctx+'/js/investor/Province.xml');                                    //对应xml文件
    $.ajax({
        type: "GET",
        url: file,
        dataType: "xml",
        timeout : 5000,
        error:function(){
        	bootbox.alert('加载配置文件失败!');
		},
        success: function(xml){
            $("#city").attr("disabled",true);
            $("#area").attr("disabled",true);
            $(xml).find("Provinces Province").each(function(i){
                var id=$(this).attr("ID");
				var name=$(this).attr("Name");
                $("#province").append("<option value='"+id+"'>"+name+"</option>");
            });
            if(id>0)
                $("#province option[value="+id+"]").attr("selected",true);
            else
                $("#province option[index=0]").attr("selected",true);
       }

    });
}

function change_province(pid,id,file){                                     //改变省份
    file = file ? file : (ctx+'/js/investor/City.xml');                                    //对应xml文件
    $.ajax({
        type: "GET",
        url: file,
        dataType: "xml",
        timeout : 5000,
        error:function(){
        	bootbox.alert('加载配置文件失败');
		},
        success: function(xml){
            $("#area").attr("disabled",true);
            $("#city").attr("disabled",true);
	        $("#area option").remove();
            $("#area").append("<option value=''>请选择区域</option>");
	        $("#city option").remove();
            $("#city").append("<option value=''>请选择城市</option>");
            if(pid != ""){
            	$("#city").removeAttr("disabled");
	            $(xml).find("Cities City[PID="+pid+"]").each(function(i){
	                var id=$(this).attr("ID");
					var name=$(this).attr("Name");
	                $("#city").append("<option value='"+id+"'>"+name+"</option>");
	            });
            }    
            if(id>0)
                $("#city option[value="+id+"]").attr("selected",true);
            else
                $("#city option[index=0]").attr("selected",true);
       }

    });
}

function change_city(pid,id,file){                                         //改变城市
    file = file ? file : (ctx+'/js/investor/Area.xml');                                    //对应xml文件
    $.ajax({
        type: "GET",
        url: file,
        dataType: "xml",
        timeout : 5000,
        error:function(){
        	bootbox.alert('加载配置文件失败!');
		},
        success: function(xml){
            $("#area").attr("disabled",true);
	        $("#area option").remove();
            $("#area").append("<option value=''>请选择区域</option>");
            if(pid != ""){
            	$("#area").removeAttr("disabled");
	            $(xml).find("Areas Area[PID="+pid+"]").each(function(i){
	                var id=$(this).attr("ID");
					var name=$(this).attr("Name");
	                $("#area").append("<option value='"+id+"'>"+name+"</option>");
	            });
            }    
            if(id>0)
                $("#area option[value="+id+"]").attr("selected",true);
            else
                $("#area option[index=0]").attr("selected",true);
       }

    });
}

$(function(){
    load_province();                                                    //加载省份
    $("#province").change(function(){                                   //更改省份
        change_province($(this).val());
    });
    $("#city").change(function(){                                       //更改城市
        change_city($(this).val());
    });
    //出生年月默认为当前时间10年前
    var date = new Date();
    var strYear = date.getFullYear() - 10;    
    var strDay = date.getDate();    
    var strMonth = date.getMonth()+1;
    if(strYear%4 == 0 && strYear%100 != 0 && strDay == 29 && strMonth == 2){   
    	strDay = 28;   
    }   
    if(strMonth<10)    
    {    
       strMonth="0"+strMonth;    
    }  
    if(strDay<10)    
    {    
       strDay="0"+strDay;    
    }  
    datastr = strYear+"-"+strMonth+"-"+strDay;  
    $("#datetimepicker").val(datastr);
})

function backList(){
	window.location.href = ctx +"/investor/list";
}

$("#btn_deal_emp_new").click(function(){
	var employeeId = $('#employeeId').val();
	var employeeName = $('#employeeName').html();
	var investorId = $('#investor_id').val();
	if (employeeId == null || employeeId == '') {
		bootbox.alert("请选择理财师！");
		return;
	}
	json = "{\"employeeId\":\""+employeeId+"\",\"investorId\":\""+investorId+"\",\"employeeName\":\""+employeeName+"\"}";
	$.ajax({
    	type:"post",
        contentType:"application/json; charset=UTF-8",
        url: ctx + "/investor/allotEmp",
        data:json,
        dataType:"json",
        success: function(msg){
        	$("#deal_emp_miss").click();
        	$.teninedialog({
                title:'系统提示',
                content:msg.message,
                showCloseButton:false,
                otherButtons:["确定"],
                otherButtonStyles:['btn-primary'],
                bootstrapModalOption:{keyboard: true},
                clickButton:function(sender,modal,index){
                	location.reload();
                }
            });
        },
        error: function (msg) {
        	bootbox.alert("服务器偷了个小懒,分配理财师失败了!");
        }
    });
});

$("#dsimiss_deal_emp").click(function(){
	location.reload();
});

//Autocomplete
$("#tags").autocomplete({
    source: function(query,process){
        $.post(ctx + "/investor/employee/"+query.term,{"matchCount":200},function(data){
        	var ebean = []
        	for (var int = 0; int < data.length; int++) {
        		var temp = [];
        		temp.label = data[int].employeeName +"  "+ data[int].employeeNo;
        		temp.value = data[int].employeeNo;
        		temp.id = data[int].employeeId;
        		temp.name = data[int].employeeName;
        		ebean.push(temp);
    		}
            return process(ebean);
        });
    },
    search:function(event, ui){
    	$("#employeeName").html('');
        $("#employeeNo").html('');
        $("#employeeId").val('');
    },
    select: function(event, ui) {
        $("#tags").val(ui.item.label);
        $("#employeeName").html(ui.item.name);
        $("#employeeNo").html(ui.item.value);
        $("#employeeId").val(ui.item.id);
        var uistr =ui.item;
        // 阻止事件的默认行为
        event.preventDefault(); 
    }
});